package com.sim.server.command.handler;

import com.sim.core.ImChannelContext;
import com.sim.core.ImConst;
import com.sim.core.ImPacket;
import com.sim.core.ImStatus;
import com.sim.core.cache.redis.JedisTemplate;
import com.sim.core.exception.ImException;
import com.sim.core.packets.Command;
import com.sim.core.packets.ForbiddenWordsReqBody;
import com.sim.core.packets.RespBody;
import com.sim.core.utils.JsonKit;
import com.sim.core.utils.ValidateUtil;
import com.sim.core.utils.ValidationResult;
import com.sim.server.command.AbstractCmdHandler;
import com.sim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 禁言/解禁
 * @Author zl
 * @Date 2021/7/29 0029
 * @Version 1.0
 **/
public class ForbiddenWordsReqHandler extends AbstractCmdHandler {

    private static Logger log = LoggerFactory.getLogger(ForbiddenWordsReqHandler.class);

    @Override
    public Command command() {
        return Command.COMMAND_FORBIDDEN_WORDS_REQ;
    }

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        if (imPacket.getBody() == null) {
            RespBody respBody = new RespBody(Command.COMMAND_FORBIDDEN_WORDS_RESP, ImStatus.C10034);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }
        ForbiddenWordsReqBody reqBody = JsonKit.toBean(imPacket.getBody(), ForbiddenWordsReqBody.class);
        ValidationResult validationResult = ValidateUtil.validateEntity(reqBody);
        if (validationResult.isHasErrors()){
            RespBody respBody = new RespBody(Command.COMMAND_FORBIDDEN_WORDS_RESP, ImStatus.C10034.getCode(), validationResult.randomErrorMsg());
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }

        // todo 判断当前用户是否有禁言解禁的权限

        try {
            JedisTemplate me = JedisTemplate.me();
            String key = ImConst.GROUP + ImConst.SUFFIX + reqBody.getGroupId() + ImConst.SUFFIX + ImConst.FORBIDDEN;
            if (reqBody.getForbiddenStatus()){
                me.sAdd(key, reqBody.getUserId());
            }else {
                me.sRem(key, reqBody.getUserId());
            }
        } catch (Exception e) {
            log.error("禁言/解禁失败：{}", e.getMessage());
        }

        return ProtocolManager.Converter.respPacket(new RespBody(Command.COMMAND_FORBIDDEN_WORDS_RESP, ImStatus.C10035), imChannelContext);
    }

}
